<template>
  <div>
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <!-- 头部输入框及俩按钮 -->
      <div class="header">
        <el-input
          v-model="input"
          placeholder="用户名"
          style="width: 179px; margin-right: 30px; height: 30px"
        ></el-input>
        <el-button
          size="defult"
          class="bt"
          type="primary"
          icon="el-icon-search"
          @click="inquireHandler"
          >查询</el-button
        >
        <el-button size="defult" class="bt" @click="clearInquireHandler">清空</el-button>
      </div>
      <!-- 中间俩按钮 -->
      <div class="main">
        <el-button class="bt" type="primary" @click="addUser">添加</el-button>
        <el-button size="defult" type="danger" :disabled="true" @click="">批量删除</el-button>
      </div>
      <!-- table展示数据 $store.getters.pageList.items -->
      <el-table
        :data="userInfoList"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column type="selection" width="50px"> </el-table-column>
        <el-table-column label="序号" width="80" align="center" type="index">
        </el-table-column>
        <el-table-column label="用户名" width="120" prop="username">
        </el-table-column>
        <el-table-column width="80" prop="nickName" label="用户昵称">
        </el-table-column>
        <el-table-column width="120" label="角色列表" prop="roleName" > </el-table-column>
        <el-table-column label="创建时间" width="300" prop="gmtCreate">
        </el-table-column>
        <el-table-column label="更新时间" width="300" prop="gmtModified">
        </el-table-column>
        <el-table-column fixed="right" width="200px" label="操作">
          <template slot-scope="scope">
            <el-button
              title="分配角色"
              type="info"
              size="mini"
              icon="el-icon-user-solid"
              @click="roleUser(scope)"
            ></el-button>
            <el-button
              title="修改用户"
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="updateUser(scope)"
            ></el-button>
            <el-button
              title="删除用户"
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="deleteUser(scope)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!--添加用户弹框  -->
      <el-dialog title="添加用户" :visible.sync="dialogTableVisible">
        <el-form
          label-width="150"
          :model="userParams"
          :rules="rulers"
          ref="formRef"
        >
          <el-form-item
            label="用户名"
            prop="username"
            style="margin-left: 20px"
          >
            <el-input
              v-model="userParams.username"
              style="width: 501px; height: 30px"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="用户昵称"
            prop="nickName"
            style="margin-left: 20px"
          >
            <el-input
              v-model="userParams.nickName"
              style="width: 501px; height: 30px"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item
            v-if="!userParams.id"
            label="用户密码"
            prop="password"
            style="margin-left: 20px"
          >
            <el-input
              v-model="userParams.password"
              style="width: 501px; height: 30px"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogTableVisible = false">取 消</el-button>
          <el-button type="primary" @click="addOrupdate">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 分配角色弹框 -->
      <el-dialog title="设置角色" :visible.sync="dialogFormVisible2">
        <el-form :model="userParams">
          <el-form-item label="用户名" label-width="150px">
            <el-input
             :disabled="true"
              v-model="activeusername"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="角色列表" label-width="150px">
            <template slot-scope="scope">
              <el-checkbox
                :indeterminate="isIndeterminate"
                v-model="checkAll"
                @change="handleCheckAllChange"
                >全选</el-checkbox
              >
              <div style="margin: 15px 0"></div>
              <el-checkbox-group
                v-model="newassignRoles"
                @change="handleCheckedCitiesChange"
              >
                <el-checkbox v-for="item in allRolesList" :label="item.id" :key="item.id">{{
                 item.roleName
                }}</el-checkbox>
              </el-checkbox-group>
            </template>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible2 = false">取 消</el-button>
          <el-button type="primary" @click="ensureHandler"
            >确 定</el-button
          >
        </div>
      </el-dialog>

      <!-- 分页器 -->
      <!--    @size-change="sizeChange"    @current-change="handler"-->
      <el-pagination
        style="margin: 20px 0"
        @size-change="sizeChange"
        @current-change="getuserInfo"
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[3, 5, 7, 9]"
        layout="prev, pager, next, jumper, ->, sizes, total"
        :total="userInfo.total"
        :pager-count="7"
      >
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
import { mapState } from "vuex";
import {reqdoAssogn,reqPageList, reqAddOrUpdateUser, reqDeleteUser,reqtoAssign ,reqNewPgeList} from "@/api/jurisdiction/users";
import { nextTick } from "process";

export default {
  data() {
    // 表单验证
    var checkusername = (rule, value, callback) => {
      console.log(value);
      if (!value) {
        return callback(new Error("请输入用户名称"));
      }
      callback();
    };
    var checknickName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入用户昵称"));
      }
      callback();
    };
    var checkpassword = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入用户密码"));
      }
      callback();
    };
    return {
      // 表单验证规则
      rulers: {
        username: [{required: true, validator: checkusername, trigger: "blur" }],
        nickName: [{required: true, validator: checknickName, trigger: "blur" }],
        password: [{required: true, validator: checkpassword, trigger: "blur" }],
      },
      //收集新增用户数据-将来发请求携带给服务器
      userParams: {
        nickName: "",
        password: "",
        username: "",
      },
      dialogTableVisible: false, //弹框显示隐藏的标识符
      dialogFormVisible2: false, //分配角色弹框是否显示的标识符
      input: '', //双向绑定输入框输入的内容
      currentPage: 1, // 默认页码(当前页码)
      pageSize: 5, // 每页记录数

      activeusername:'',//当前选中的角色名称
      allRolesList:[],//现有的角色列表数组
      assignRoles:[],//当前用户选中的角色组成的列表
      newassignRoles:[],//存放选中的id的数组
      str:'',//存放字符串结构的角色id
      str2:'',//存放字符串结构的当前用户id

      checkAll: false,
      isIndeterminate: true,
      userInfo:[],//存放列表数据
      userInfoList:[]//存放列表数据的数组
    };
  },
  methods: {
    // 获取表格中数据
    // async handler(pager = 1) {
    //   this.currentPage = pager;
    //   await this.$store.dispatch("getUserInfo", {
    //     page: this.currentPage,
    //     limit: this.pageSize,
    //   });
    // //   console.log(this.$store);
    // //   console.log(this.$store.getters.pageList.items);
    // },
   async getuserInfo(pager = 1){
    this.currentPage = pager;   
   let result  = await  reqPageList(this.currentPage, this.pageSize)
//    console.log(result);
// 存储数据
   this.userInfo = result.data
   this.userInfoList = result.data.items
    },

    // 分页器右侧一页几条数据发生变化的回调
    sizeChange(limit) {
      // console.log(limit);
      this.pageSize = limit;
      this.getuserInfo();
    },

    // 点击添加按钮的事件回调
    addUser() {
      // 对话框弹出
      this.dialogTableVisible = true;
      //每一次对话框显示出来的时候，先清空数据[把上一次收集的数据不要了，重新收集]
      this.userParams.username = "";
      this.userParams.password = "";
      this.userParams.nickName = "";
      //nextTick:当响应式数据发生变化[页面重新渲染],获取更新后的DOM
      nextTick(() => {
        // console.log(this.$refs);
        // 表单清空
        this.$refs.formRef.resetFields();
      });
    },

    // 新增或修改用户数据 弹框确定按钮的事件回调
    addOrupdate() {
      //触发el-form组件实例的validate方法
      //全部字段进行校验
      this.$refs.formRef.validate(async (success) => {
        // 如果全部字段校验成功
        if (success) {
          // 发请求
          await reqAddOrUpdateUser(this.userParams);
          // 对话框关闭
          this.dialogTableVisible = false;
          // 再次获取用户最新数据
          this.getuserInfo(this.userParams.id ? this.currentPage : 1);
          // 成功的信息
          this.$message({
            message: this.userParams.id ? "修改用户成功" : "新增用户成功",
            type: "success",
          });
        }
      });
    },

    // 表格最后一列的修改按钮的事件回调
    updateUser(scope) {
      this.dialogTableVisible = true;
      //收集修改 已有用户 数据
      nextTick(() => {
        //重置初始化，再次重新赋值
        //重置该表单项，将其值重置为初始值，并移除校验结果
        this.$refs.formRef.resetFields();
        this.userParams.id = scope.row.id;
        this.userParams.username = scope.row.username;
        this.userParams.nickName = scope.row.nickName;
      });
    },

    // 表格最后一列的删除按钮的事件回调
    deleteUser(scope) {
      this.$confirm("您确定要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          // 删除品牌成功发请求
          await reqDeleteUser(scope.row.id);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          // 再次获取最新数据  留在当前页
          this.getuserInfo(this.currentPage);
        })
        .catch(() => {});
    },

    // 点击表格最后一列的分配角色的事件回调
  async  roleUser(scope) {
      this.dialogFormVisible2 = true;
      let result = await reqtoAssign(scope.row.id)
      console.log(result);
    //   存储数据
      this.activeusername = scope.row.username
      this.allRolesList = result.data.allRolesList
      this.assignRoles = result.data.assignRoles
    //   console.log( this.assignRoles);
      this.newassignRoles = this.assignRoles.map(item=>{
        return item.id
      })
      // console.log(this.newassignRoles);
  
      // 用户id
      this.str2= scope.row.id
      // console.log(str);
    //   再次获取列表数据
      // this.getuserInfo()
    //   console.log(scope.row.id);
    //   console.log(result);
    },

    // 分配角色弹框中的确定按钮事件回调
  async  ensureHandler(){
        // 角色id
        this.str = this.newassignRoles.toString()
        this.dialogFormVisible2 = false;
        // console.log(str);
        await reqdoAssogn(this.str2,this.str)
        // 重新获取列表数据
        this.getuserInfo()

    },

    // 全选组件的事件回调
    handleCheckAllChange(val) {
        this.assignRoles = val ? allRolesList : [];
        this.isIndeterminate = false;
      },
      handleCheckedCitiesChange(value) {
        let checkedCount = value.length;
        this.checkAll = checkedCount === this.allRolesList.length;
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.allRolesList.length;
      },

    // 查询按钮的事件回调
   async inquireHandler(){
   try {
        let result  = await reqNewPgeList(this.currentPage, this.pageSize,this.input)
        console.log(result);
        this.userInfoList = result.data.items
        this.userInfo = result.data  
   } catch (error) {
   }
    },

    // 清空按钮的事件回调
 clearInquireHandler(){
    this.getuserInfo()
    this.input = ''
    }

  },
  computed: {
    ...mapState({ pageList: (state) => state.users.pageList }),
  },
  // 挂载
  mounted() {
    this.getuserInfo();
  },
};
</script>

<style>
.bt {
  text-align: center;
  margin: 0 auto;
}
.main {
  margin: 20px 0;
}
</style>
